package cn.com.wangluotongxin.merchants.controller;

import cn.com.wangluotongxin.common.constants.CommonConstant;
import cn.com.wangluotongxin.common.web.AjaxResult;
import cn.com.wangluotongxin.merchants.service.IMerchantsMenuService;
import cn.com.wangluotongxin.merchants.vo.MenuVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商户管理-菜单权限 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-05-17
 */
@Api(tags = "商户管理-菜单权限 相关接口")
@RestController
@RequestMapping("/menu")
public class MerchantsMenuController {

    @Autowired
    private IMerchantsMenuService menuService;

    @ApiOperation("列表(树形)")
    @GetMapping("/tree/list")
    public AjaxResult<List<MenuVo>> tree(){
        List<MenuVo> menuVos = menuService.getTreeList();
        List<MenuVo> treeMenuVos = treeBuilders(menuVos);
        return AjaxResult.success(treeMenuVos);
    }

    private List<MenuVo> treeBuilders(List<MenuVo> menuVoList) {
        List<MenuVo> menuVos = new ArrayList<>();
        for (MenuVo menuVo : menuVoList) {
            if (Objects.equals(CommonConstant.ZERO, menuVo.getParentId())) {
                menuVos.add(menuVo);
            }
            for (MenuVo menu : menuVoList) {
                if (menu.getParentId().equals(menuVo.getId())) {
                    if (menuVo.getChildren() == null) {
                        menuVo.setChildren(new ArrayList<>());
                    }
                    menuVo.getChildren().add(menu);
                }
            }
        }
        return menuVos;
    }
}